package com.zz.service;

import org.example.dto.StudentInfoDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class StudentCacheService {

    private final RedisTemplate<String, Object> redisTemplate;

    // 构造器注入
    public StudentCacheService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 存入缓存
    public void cacheStudent(StudentInfoDTO student) {
        String key = "student:" + student.getMachineId(); // 使用ID作为key的一部分
        redisTemplate.opsForValue().set(key, student, 1, TimeUnit.HOURS); // 设置1小时过期
    }

    // 从缓存获取
    public StudentInfoDTO getStudentFromCache(String studentId) {
        String key = "student:" + studentId;
        return (StudentInfoDTO) redisTemplate.opsForValue().get(key);
    }

    // 删除缓存
    public void removeStudentFromCache(String studentId) {
        String key = "student:" + studentId;
        redisTemplate.delete(key);
    }
}